package com.roads.supervisor.controller;

import com.roads.common.annotation.Log;
import com.roads.common.constant.Constants;
import com.roads.common.core.controller.BaseController;
import com.roads.common.core.domain.AjaxResult;
import com.roads.common.core.domain.entity.SysUser;
import com.roads.common.enums.BusinessType;
import com.roads.common.utils.DateUtils;
import com.roads.common.utils.StringUtils;
import com.roads.project.domain.ProInstitution;
import com.roads.project.service.IBidService;
import com.roads.supervisor.domain.SupPeriod;
import com.roads.supervisor.domain.summary.SupSummaryRecord;
import com.roads.supervisor.domain.summary.SupSummaryRecordUserVo;
import com.roads.supervisor.domain.summary.SupSummaryVo;
import com.roads.supervisor.service.ISupPeriodService;
import com.roads.supervisor.service.ISupSummaryService;
import com.roads.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @ClassName SupSummaryController
 * @Description 监理汇总controller
 * @Author nhp
 * @Date 2022/7/14 0014 17:56
 * @Version 1.0.0
 **/
@RestController
@RequestMapping("/supervisor/summary")
public class SupSummaryController extends BaseController {

    @Autowired
    private ISupSummaryService summaryService;

    @Autowired
    private IBidService bidService;

    @Autowired
    private ISupPeriodService periodService;

    @Autowired
    private ISysUserService userService;

    /**
     * 汇总前验证登录用户
     *
     * @return 结果
     */
    @GetMapping("/beforeSummaryValidate")
    public AjaxResult beforeSummaryValidate() {
        int count = summaryService.getCountWorkflowNodeUser(getUsername());
        if (count == 0) {
            return error("当前登录用户无法进行汇总操作，请联系管理员");
        }
        return success();
    }

    /**
     * 汇总初始化
     *
     * @return 结果
     */
    @GetMapping("/init")
    public AjaxResult init() {
        long startTime = System.currentTimeMillis();
        AjaxResult ajaxResult = new AjaxResult();
        String userName = getUsername();
        List<ProInstitution> bids = bidService.selectSummarySupervisorBid(userName);
        ajaxResult.put("bids", bids);
        if (bids.size() > 0) {
            String institutionCode = bids.get(0).getInstitutionCode();
            ajaxResult.put("institutionCode", institutionCode);
            SupPeriod search = new SupPeriod();
            search.setInstitutionCode(institutionCode);
            List<SupPeriod> periods = periodService.selectModelList(search);
            ajaxResult.put("periods", periods);
            if (periods.size() > 0) {
                //获取当前计量期次
                SupPeriod currentPeriod = periodService.getCurrentPeriod(institutionCode);
                if (StringUtils.isNull(currentPeriod)) {
                    ajaxResult.put("periodName", periods.get(0).getPeriodName());
                } else {
                    ajaxResult.put("periodName", currentPeriod.getPeriodName());
                }
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("汇总初始化耗时：" + (endTime - startTime) + " ms");
        return ajaxResult;
    }

    /**
     * 数据汇总
     *
     * @param model 汇总对象
     * @return 结果
     */
    @PreAuthorize("@ss.hasPermi('supervisor:meterage:summary')")
    @Log(title = "监理计量", businessType = BusinessType.SUMMARY)
    @PostMapping("/summary")
    public AjaxResult summary(@RequestBody SupSummaryVo model) {
        // 验证用户是否可以汇总
        SysUser loginUser = userService.selectUserById(getUserId());
        model.setUserName(loginUser.getUserName());
        model.setCreateByName(loginUser.getNickName());
        model.setSummaryDate(DateUtils.getNowDate());
        System.out.println("标段编号：" + model.getInstitutionCode());
        System.out.println("工期：" + model.getPeriodName());
        System.out.println("是否批复：" + model.getIsApprove());
        // 如果本期已经汇总批复，将无法进行监理计量汇总--如果业主进行解锁汇总则不进行限制
        SupPeriod period = periodService.getPeriodByPeriodName(model.getInstitutionCode(), model.getPeriodName());
        if (Constants.YES.equals(period.getIsLock())) {
            SupSummaryRecord approveRecord = summaryService.getSummaryRecordByApprove(model.getInstitutionCode(), model.getPeriodName());
            if (StringUtils.isNotNull(approveRecord) && !approveRecord.getCreateBy().equals(model.getUserName())) {
                return AjaxResult.error("本期已批复汇总，无法进行汇总操作");
            }
        }
        // 查看上一期是否最终批复，如果未最终批复，则不能进行本期汇总
        if (!Constants.FIRST_PERIOD.equals(model.getPeriodName())) {
            String lastPeriodName = String.valueOf(Integer.parseInt(model.getPeriodName()) - 1);
            boolean result = summaryService.getSummaryIsApprove(model.getInstitutionCode(), lastPeriodName);
            if (!result) {
                return error("请先批复汇总上一期数据后，才能进行本期数据汇总操作");
            }
        }
        return toAjax(summaryService.summary(model));
    }

    /**
     * 根据机构编号，工期名称，获取汇总用户集合
     *
     * @param institutionCode 机构编号
     * @param periodName 工期
     * @return 结果
     */
    @PostMapping("/dropDownReportUserList")
    public AjaxResult dropDownReportUserList(String institutionCode, String periodName) {
        AjaxResult ajaxResult = new AjaxResult();
        List<SupSummaryRecordUserVo> list = summaryService.selectSummaryRecordUserList(institutionCode, periodName);
        ajaxResult.put("users", list);
        if (list.size() > 0) {
            //获取当前计量期次
            ajaxResult.put("user", list.get(0).getUser());
        }
        return ajaxResult;
    }

    /**
     * 获取汇总记录是否批复
     *
     * @param institutionCode 机构编号
     * @param periodName 工期
     * @param user 用户
     * @return 结果
     */
    @PostMapping("/getSummaryRecordIsApprove")
    public AjaxResult getSummaryRecordIsApprove(String institutionCode, String periodName, String user) {
        SupSummaryRecord search = new SupSummaryRecord();
        search.setInstitutionCode(institutionCode);
        search.setPeriodName(periodName);
        search.setCreateBy(user);
        SupSummaryRecord summaryRecord = summaryService.getSummaryRecord(search);
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.put("isApprove", summaryRecord.getIsApprove());
        return ajaxResult;
    }

}
